import requests
from bs4 import BeautifulSoup
import pandas as pd
import re


def fetch_dividend_table(stock_code: str) -> pd.DataFrame:
    """
    根据香港股票的分红数据
    数据源头：新浪
        https://stock.finance.sina.com.cn/hkstock/dividends/00008.html
    参数:
        stock_code (str): 股票代码，如 "00008"

    返回:
        pd.DataFrame: 包含表格数据的 DataFrame
    """
    url = f"https://stock.finance.sina.com.cn/hkstock/dividends/{stock_code}.html"
    headers = {
        "Referer": f"https://stock.finance.sina.com.cn/hkstock/finance/{stock_code}.html",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0"
    }

    response = requests.get(url, headers=headers)
    response.encoding = 'gbk'

    soup = BeautifulSoup(response.text, "html.parser")
    table = soup.find("table", class_="tab05")
    if not table:
        raise ValueError("未找到目标表格")

    rows = table.find_all("tr")
    headers = [th.get_text(strip=True) for th in rows[0].find_all("td")]

    data = []
    for row in rows[1:]:
        cols = [td.get_text(strip=True) for td in row.find_all("td")]
        data.append(cols)

    df = pd.DataFrame(data, columns=headers)
    return df


def process_dividend_data(df: pd.DataFrame) -> pd.DataFrame:
    """
    处理原始分给表格，提取数值并按年度合计

    参数:
        df (pd.DataFrame): 包含 "年度"、"消息内容"等列的原始数据

    返回:
        pd.DataFrame: 按年度结果合计后的 DataFrame
    """

    def extract_amount(text):
        """
        从字符串中提取“港元”前面的数字金额
        """
        match = re.search(r'([0-9.]+)\s*港元', text)
        if match:
            return float(match.group(1))
        return None

    df = df.copy()
    df["派息金额"] = df["派息内容"].apply(extract_amount)
    summary = df.groupby("年度")["派息金额"].sum().reset_index()
    summary = summary.rename(columns={"派息金额": "年度合计派息"})
    return summary


# 使用示例
# df = fetch_dividend_table("00008")
# print(df)
if __name__ == '__main__':
    # df = fetch_dividend_table("00008")
    # print(df)
    df = fetch_dividend_table("00883")
    print(df)

    df = process_dividend_data(df)
    print(df)
